const app = getApp();
import fetch, { upload } from "../../utils/fetch";

Page({
  data: {
    tempFilePaths: [],
    form: {
      name: '',
      gender: 2,
      wechat: '',
      info: '',
      file_ids: [],
      config: {
        show: false
      }
    }
  },
  onLoad: function (options) {
    this.setData({
      config: {
        show: options.show
      }
    });
  },
  radioChange: function (e) {
    const form = this.data.form;
    form.gender = e.detail.value;
    this.setData({
      form: form
    });
  },
  bindNameInput: function (e) {
    const form = this.data.form;
    form.name = e.detail.value;
    this.setData({
      form: form
    })
  },
  bindWechatInput: function (e) {
    const form = this.data.form;
    form.wechat = e.detail.value;
    this.setData({
      form: form
    })
  },
  bindInfoInput: function (e) {
    const form = this.data.form;
    form.info = e.detail.value;
    this.setData({
      form: form
    })
  },
  chooseImage: function () {
    var that = this;
    wx.chooseImage({
      count: 9, // 默认9
      sizeType: ["original", "compressed"], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ["album", "camera"], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths;
        for (var i = 0; i < tempFilePaths.length; i++) {
          that.data.tempFilePaths.push(tempFilePaths[i]);

          upload(`/api/file/add`, 'file', tempFilePaths[i]).then(res => {
            const json = JSON.parse(res.data);
            if (res && json.code) {
              const file_ids = that.data.form.file_ids;
              file_ids.push(json.data);
              that.setData({
                file_ids: file_ids
              });
            }
          });
        }
        that.setData({
          tempFilePaths: that.data.tempFilePaths
        });
      }
    });
  },
  onShareAppMessage: function (res) {
    return {
      title: `小红娘帮Ta牵线，认识了Ta这么多年，Ta还没有对象，帮Ta找个对象吧。`,
      path: `/pages/product/product?show=true`,
      success: function (res) {
        // 转发成功
      },
      fail: function (res) {
        // 转发失败
      }
    }

  },
  submit: function () {
    if (!this.data.form.name) {
      wx.showModal({
        content: 'Ta的名字不能为空',
        showCancel: false
      });
      return;
    }

    var that = this;
    wx.showModal({
      content: '点击【我要发布】之后将自动跳转到Ta的主页，请立即点击【帮Ta牵线】发送给朋友或朋友圈。',
      showCancel: false,
      success: function (res) {
        fetch(`/api/lover/add`, that.data.form).then(res => {
          if (res && res.data.code) {
            wx.navigateTo({
              url: `/pages/index/index?id=${res.data.data.id}`,
            })
          }
        });
      }
    });
  }
});
